package siteManage

import (
	"bufio"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"main/src/apps"
	"main/src/utils"
	"mime/multipart"
	"strconv"
	"time"
)

type CreateSiteDto struct {
	URL string `json:"url" binding:"required,min=1"` // 域名 URL
	Cat int    `json:"cat"`
}

type SiteInfoResponseDto struct {
	Id        int       `json:"id"`
	UserID    int       `json:"user_id"`   // 所属用户 ID
	URL       string    `json:"url"`       // 域名 URL
	IsActive  bool      `json:"is_active"` // 是否存活
	Cat       int       `json:"cat"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

func (dto *SiteInfoResponseDto) format(domain Domain) {
	dto.Id = domain.Id
	dto.UserID = domain.UserID
	dto.Cat = domain.Cat
	dto.IsActive = domain.IsActive
	dto.UpdatedAt = domain.UpdatedAt
	dto.CreatedAt = domain.CreatedAt
	dto.URL = domain.URL
}

func (dto *CreateSiteDto) Create(c *gin.Context) (res SiteInfoResponseDto, err error) {
	var ctxUser, _ = c.Get("user")
	model := &Domain{
		UserID: ctxUser.(utils.UserJWTInfo).Id,
		URL:    dto.URL,
		Cat:    dto.Cat,
	}
	result := apps.DB.Create(model)
	err = result.Error
	if err != nil {
		utils.Response(
			c,
			"插入失败err: "+err.Error(),
			utils.Status.Error,
			nil,
		)
	} else {
		res.format(*model)
	}
	return res, err
}

type GetSiteDto struct {
	utils.GetDataLimitDto
}

func (dto *GetSiteDto) Get(c *gin.Context) (responseDto utils.GetDataLimitResponseDto, err error) {
	dto.Init()

	if dto.PageNum < 0 {
		utils.Response(c, "page_num < 0", utils.Status.Error, nil)
		return responseDto, errors.New("page < 0")
	}
	var ctxUser, _ = c.Get("user")
	userJWTInfo := ctxUser.(utils.UserJWTInfo)
	var whereStr = ""
	if !userJWTInfo.IsSuper {
		whereStr += "user_id = " + strconv.Itoa(userJWTInfo.Id)
	}
	var models []Domain
	var contents []*SiteInfoResponseDto
	var count int64
	apps.DB.Model(&Domain{}).Where(whereStr).Count(&count).Limit(dto.PageSize).Offset((dto.PageNum - 1) * dto.PageSize).Find(&models)

	for i := range models {
		temp := &SiteInfoResponseDto{}
		temp.format(models[i])
		contents = append(contents, temp)
	}
	responseDto.Init(dto.GetDataLimitDto, count, contents)
	return responseDto, err
}

type UpdateSiteDto struct {
	Id  int    `json:"id" binding:"required"`
	URL string `json:"url"` // 域名 URL
	Cat string `json:"cat"`
}

func (dto *UpdateSiteDto) UpdateContent(c *gin.Context) (ctn *SiteInfoResponseDto, err error) {
	content := &Domain{Id: dto.Id}
	result := apps.DB.Where(content).Find(&content)
	if result.Error == nil && len(content.URL) > 0 {
		if dto.URL != "" {
			content.URL = dto.URL
		}
		if dto.Cat != "" {
			content.Cat, _ = strconv.Atoi(dto.Cat)
		}
		result = apps.DB.Save(&content)
		err = result.Error
	}
	if err == nil && result.RowsAffected == 0 {
		err = errors.New("该数据以删除，或没有该ID")
	}
	if err != nil {
		utils.Response(
			c,
			"更新失败err: "+err.Error(),
			utils.Status.Error,
			nil,
		)
	} else {
		res := SiteInfoResponseDto{}
		res.format(*content)
		return &res, err
	}
	return nil, err
}

type DeleteSiteDto struct {
	Id int `json:"id" binding:"required"`
}

func (dto *DeleteSiteDto) DeleteDomain(c *gin.Context) (err error) {
	result := apps.DB.Delete(&Domain{Id: dto.Id})

	err = result.Error
	if err != nil {
		utils.Response(
			c,
			"删除失败err: "+err.Error(),
			utils.Status.Error,
			nil,
		)
	}
	return err
}

type ExportFileByDomain struct {
	File *multipart.FileHeader
	Cat  int `form:"cat"`
}

func (e *ExportFileByDomain) Export(c *gin.Context) (ctn []SiteInfoResponseDto, err error) {
	// 打开文件
	f, err := e.File.Open()
	if err != nil {
		utils.Response(c, fmt.Sprintf("打开文件失败：%s", err.Error()), utils.Status.Error, nil)
		return
	}
	defer f.Close()
	ctn = []SiteInfoResponseDto{}
	// 逐行读取文本内容
	scanner := bufio.NewScanner(f)
	var ctxUser, _ = c.Get("user")
	userJWTInfo := ctxUser.(utils.UserJWTInfo)
	for scanner.Scan() {
		line := scanner.Text()
		domain := Domain{
			URL:    line,
			Cat:    e.Cat,
			UserID: userJWTInfo.Id,
		}
		apps.DB.Create(&domain)
		log.Println(line)
	}
	return ctn, err
}
